# encoding=utf-8
import os
import xml.etree.ElementTree as ET
import shutil
from tqdm import tqdm


def check_empty(xml_file):
    xml_tree = ET.parse(xml_file)
    xml_root = xml_tree.getroot()
    object_ele = xml_root.findall("object")
    if len(object_ele) == 0:
        print(xml_file)
        return 1
    else:
        return 0


def mkdir_dir(directory_path):
    if not os.path.exists(directory_path):
        os.mkdir(directory_path)


if __name__ == "__main__":
    anno_storage = r"/home/kaijia/algo-env/datasets/hq_safeguard_dataset/VOC/Annotations"
    xml_list = os.listdir(anno_storage)
    # empty_list = []
    # 创建暂存目录
    storage_path = os.path.dirname(anno_storage)
    tem_storage = os.path.join(storage_path, r"temporary")
    mkdir_dir(tem_storage)
    pic_storage = os.path.join(storage_path, r"Images")
    for xml in tqdm(xml_list):
        xml_abs = os.path.join(anno_storage, xml)
        flag = check_empty(xml_abs)
        if flag:
            xml_tem = os.path.join(tem_storage, xml)
            shutil.move(xml_abs, xml_tem)
            file_name, file_suffix = os.path.splitext(xml)
            pic_abs = os.path.join(pic_storage, file_name + ".jpg")
            pic_tem = os.path.join(tem_storage, file_name + ".jpg")
            shutil.move(pic_abs, pic_tem)
    #         empty_list.append(file_name)
    # print(len(empty_list))
    # print(empty_list)
